<template>
  <div id="app" class="app-content csp">
    <div v-if="isLoding">
      <van-cell class="text-center  customer-loading">
        <van-row>
          <van-col>
            <van-row>
              <van-col span="24"><img :src="lodingImgSrc" width="100px"></van-col>
              <van-col span="24">客服MM正在接驾中...</van-col>
            </van-row>
          </van-col>
        </van-row>

      </van-cell>

    </div>
    <div v-else>
      <nav-bar :backtype.sync="isOpenProblem" :isCenterPage.sync="isCenterPage"/>
      <div v-if="isOpenProblem&&customerActive==0" class="customer-openProblem">

        <van-row>
          <van-col span="24">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <span class="f-s-17">猜您想问：</span>
          </van-col>
        </van-row>
        <van-row>
          <van-col span="24" v-for="(value, key) in openProblemData.items">
            <van-row>
              <van-col span="24">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class=" color-origin">{{value.title}}</span>
              </van-col>
              <van-col span="24">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span>答：{{value.answer}}</span>
              </van-col>
              <van-col span="24">&nbsp;</van-col>
            </van-row>
          </van-col>
        </van-row>
        <van-row>
          <van-col span="24" class="text-center" >
            <span>若仍有{{problemType_[openProblemData.id]}}疑问，请点此反馈
              <van-button class="min" type="warning" @click="customerOpenProblemPage(openProblemData)">{{openProblemData.btnname}}</van-button></span>
          </van-col>
          <van-col span="24">&nbsp;</van-col>
        </van-row>
      </div>
      <div v-else-if="customerActive==0&& showPImg">
        <van-notice-bar wrapable :scrollable="false">
          请正确选择您要咨询的问题类型，以便相应的问题专家快速为您解决～
        </van-notice-bar>
        <div>
          <van-row class="text-center">
            <van-col class="customer-center-margin" span="12" v-for="(value, key) in customerProblemGroup">
              <van-row>
                <van-col span="24">
                  <img :src="problemImage[value.id]" width="65px" height="65px" @click="openProblem(value)"></van-col>
                <van-col span="24">
                  <span @click="openProblem(value)">{{value.desc}}</span></van-col>
              </van-row>
            </van-col>
          </van-row>

        </div>
      </div>
      <div v-else>
        <van-notice-bar wrapable :scrollable="false">
          问题处理一般需要5～10分钟，部分问题可能需要更久，客服MM会第一时间回复您，请耐心等待，稍安勿躁哦～
        </van-notice-bar>
        <van-pull-refresh v-model="isRefresh" @refresh="onRefresh" :animation-duration="10" >

        <van-cell-group class="openRecordData " v-if="openRecordData.length >0 && showNewData">

          <van-cell  v-for="(value, key) in openRecordData" @click="(value.status===1)?openPopupDetail(value):''">

            <van-swipe-cell :on-close="onClose(value.id)" :right-width="value.status===1?SwipeCellLeft:0" >

              <van-row>
                <div @click="(value.status===0)?openPopupDetail(value):''">
                  <van-col span="5">
                    <div :class="value.checked===0? 'van-tabbar-item__icon van-tabbar-item__icon--dot unread-dot':''" style="text-align: center;">
                      <van-button :type="recordClass[value.status]" round class="circle ">{{recordStatus[value.status]}}</van-button>
                    </div>
                  </van-col>
                  <van-col span="10">
                    <van-row>
                      <van-col span="24" class="f-s-12">{{problemType[value.type_id]}}</van-col>
                      <van-col span="24" class="f-s-12">{{value.created_at}}</van-col>
                    </van-row>
                  </van-col>
                </div>
                <van-col span="9">
                  <van-row v-if="value.status===0" style="line-height: 48px;text-align: center;">
                    <van-button class="min disabled Expedited" type="danger" @click="expedited(value)" :disabled="!istimedisabled(value)">申请加急</van-button>
                  </van-row>
                  <van-row v-if="value.status===1">
                    <van-col span="24" class="f-s-12 " :class="evaluationClass[value.comment]">{{evaluationStatus[value.comment]}}</van-col>
                    <van-col span="24" class="f-s-12">{{value.updated_at}}</van-col>
                  </van-row>
                </van-col>
              </van-row>

              <template slot="right" v-if="value.status===1">
                <van-button square type="danger" text="确认删除" />
              </template>
            </van-swipe-cell>
          </van-cell>
        </van-cell-group>
        <div  v-else-if="!showNewData" class="text-center nonumber rdataloading" >
            <div class="rdataloading-center">
                <van-loading size="17px"/><span class="loadingtxt">加载中...</span>
            </div>
        </div>
          <div class="text-center nonumber" v-else-if="openRecordData.length===0 && showNewData">您当前还没有反馈记录哦～</div>
        </van-pull-refresh>
        <van-popup v-model="showPopup" class="showPopup ">
          <img class="closePopup" src="../../assets/close2.png" @click='closePopupData()'>
          <van-row class="customer-openProblem PopupHg">
            <van-col span="24">{{openPopupData.created_at}}提交：</van-col>
            <van-col span="24" class="col-br">&nbsp;</van-col>
            <van-col span="24">问题类型：{{problemType[openPopupData.type_id]}}</van-col>
            <van-col span="24" v-if="openPopupData.game">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">游戏分类：{{propGame[openPopupData.game]}}</van-col>
            </van-col>
            <van-col span="24" v-if="openPopupData.question_type">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">问题分类：{{problemChildType[openPopupData.question_type]}}</van-col>
            </van-col>
            <van-col span="24" v-if="openPopupData.desc&&openPopupData.question_type!==201">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24" v-html="'问题详细描述：'+openPopupData.desc"></van-col>
            </van-col>
            <van-col span="24" v-if="openPopupData.appear_at">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">问题出现时间：{{openPopupData.appear_at}}</van-col>
            </van-col>
            <!--提现问题-->
            <van-col span="24" v-if="openPopupData.type_id===2&&openPopupData.question_type!==202">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">提现单号：{{openPopupData.withdraw_id}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">提现时间：{{openPopupData.withdraw_at}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">提现金额：{{openPopupData.amount}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24" v-html="openPopupData.desc?'补充说明：'+openPopupData.desc:'补充说明：'"></van-col>
            </van-col>
            <!--商务合作-->
            <van-col span="24" v-if="openPopupData.type_id===5 && openPopupData.cooperation">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">联系方式：{{contactType[openPopupData.cooperation.contact_type]}} &nbsp;{{openPopupData.cooperation.contact_account}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">拥有的资源：{{openPopupData.cooperation.source_desc}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">之前是否有棋牌推广经验：{{istrue[openPopupData.cooperation.is_veteran]}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">当前是否拥有下级团队：{{istrue[openPopupData.cooperation.with_lower]}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">下级团队人数：{{proSubordinateTeamNum[openPopupData.cooperation.lower_count]}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">预计每天可带来多少新用户：{{propNewUser[openPopupData.cooperation.daily_new]}}</van-col>
            </van-col>
            <!--充值问题-->
            <van-col span="24" v-if="openPopupData.type_id===1">
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">充值单号：{{openPopupData.pay_id}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">付款时间：{{openPopupData.pay_at}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">充值金额：{{openPopupData.amount}}</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24">付款姓名：{{openPopupData.pay_name}}</van-col>
            </van-col>

            <van-col span="24" v-if="openPopupData.images&&openPopupData.images.length!==0">
              <van-row>
                <van-col span="24" class="col-br">&nbsp;</van-col>
                <van-col span="24">附件：</van-col>
                <van-col span="24">
                  <img :src="value" class="problemimg" @click="showCustomImagePreview(openPopupData.images,key)" v-for="(value, key) in openPopupData.images" :key="value">
                </van-col>
              </van-row>
            </van-col>
            <van-col span="24" v-if="openPopupData.checked!=null">
              <van-col span="24" class="border-bottom-grey">&nbsp;</van-col>
              <van-col span="24" class="color-Gold"  >{{openPopupData.updated_at}}回复：</van-col>
              <van-col span="24" class="col-br">&nbsp;</van-col>
              <van-col span="24" v-if="openPopupData.response"  >
                <div @click="openurl($event)" v-html="openPopupData.response"></div>
              </van-col>


              <van-col span="24" class="col-br">&nbsp;</van-col>

              <van-col span="24" class="col-br" v-if="openPopupData.comment===null ">
                <van-col span="24">为提高服务质量，请您为本次服务作出评价：</van-col>
                <van-tabbar :fixed="false" class="tabbar">
                                              <van-tabbar-item > <van-button  class="min type-blue-1 w-100" @click="setGood(openPopupData,2)"><i class="cubeic-bad"></i>不满意</van-button></van-tabbar-item>
                                              <van-tabbar-item ><van-button type="warning" class="min w-100"  @click="setGood(openPopupData,1)"><i class="cubeic-good"></i>满意</van-button></van-tabbar-item>
                </van-tabbar>
              </van-col>
              <van-col span="24" v-else class="text-center">你已对本次服务作出评价：{{isGood[openPopupData.comment]}}</van-col>
            </van-col>
          </van-row>

        </van-popup>
      </div>

      <van-tabbar :fixed="false" class="border-none"></van-tabbar>
      <van-tabbar v-model="customerActive" active-color="#ed6a0c" inactive-color="#000">
        <van-tabbar-item @click="customeradvisory">
          <span>客服咨询</span>
          <img  slot="icon" slot-scope="props" src="../../assets/customerService/custom2.png">
        </van-tabbar-item>
        <van-tabbar-item :info="feedBackRecordInfo" @click="feedBackRecord" >
          <span>反馈记录</span>
          <img slot="icon" slot-scope="props" src="../../assets/customerService/record.png">
        </van-tabbar-item>
      </van-tabbar>
    </div>
  </div>
</template>

<script>
import {SwipeCell,Loading,Toast,PullRefresh, Row, Col, NoticeBar, CellGroup, Cell, Button, Tabbar, TabbarItem, Icon, Popup } from 'vant'
import NavBar from '@/components/customerService/NavBar.vue'
import { deleteworkorder,getProblemType, getCommonProblem, getUncheckedCount, urgentworkorder, getworkorderlist, getworkorderdetail, setcommnet, announcementAlert } from '@/api/customerService'
import { touches } from '@/utils/touches'
import {setQuery,getQuery } from '@/utils/auth'
import {openurl} from '@/utils/openurl'


export default {
  components: {
    NavBar,
    [Loading.name]: Loading,
    [Toast.name]: Toast,
    [PullRefresh.name]: PullRefresh,
    [Row.name]: Row,
    [Col.name]: Col,
    [NoticeBar.name]: NoticeBar,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [SwipeCell.name]: SwipeCell,
  },
  filters: { },
  data () {
    return {
      isOpenPopupDetail:true,
      SwipeCellLeft:90,
      isRefresh: false,
      isCenterPage:true,
      customIndex: 0,
      customerProblemGroup: [],
      isLoding: true,
      lodingImgSrc: require('../../assets/customerService/custom1.png'),
      isOpenProblem: false,
      openProblemData: [],
      customerActive: 0,
      backtype: '',
      showNewData: false,
      showPImg:true,
      openRecordData: [],
      openPopupData: {},
      avatar: '',
      Timeout_: '',
        problemImage:this.$store.state.app.problemImage,
      propGame: this.$store.state.app.propGame_,
      contactType: this.$store.state.app.contactType_,
      istrue: this.$store.state.app.istrue_,
      proSubordinateTeamNum: this.$store.state.app.proSubordinateTeamNum_,
      propNewUser: this.$store.state.app.propNewUser_,
      isGood: this.$store.state.app.isGood,
      openPage: {
        1: 'rechargeStatement',
        2: 'withDraw',
        3: 'accountFeedback',
        4: 'gameFeedback',
        5: 'BusinessCooperation',
        6: 'problemsubmission',
      },
      problemType_: this.$store.state.app.problemType_,
      recordStatus: this.$store.state.app.recordStatus,
      evaluationStatus: this.$store.state.app.evaluationStatus,
      recordClass: {
        0: 'warning',
        1: 'primary',
      },
      evaluationClass: {
        1: 'color-green',
        2: 'color-green',
        null: 'color-red'
      },
      problemType: this.$store.state.app.problemType,
      problemChildType: this.$store.state.app.problemChildType,
      feedBackRecordInfo: '',
      showPopup: false,
    }
  },
  created () {
    this.IsInfo()
  },
  mounted () {
    setQuery(this.$router.history.current.query)
    touches();

  },
  methods: {
    onClose(id) {
      let this_=this;
      return (clickPosition, instance,detail) => {
        switch (clickPosition) {
          case 'left':
          case 'cell':
          case 'outside':
            this_.isOpenPopupDetail=false;
            instance.close()
            break;
          case 'right':
            this.closeRecord(id);
            instance.close();
            break;
        }
      }
    },
    async closeRecord(id){
      await deleteworkorder(id)
      this.feedBackRecord();
      this.getFeedBackRecordInfo();
    },
    onRefresh() {
      setTimeout(() => {
        this.$toast('刷新成功');
        this.isRefresh = false;
        this.feedBackRecord();
      }, 500);
    },
    istimedisabled (value) {
      //发起时间加5分钟小于等于当前时间就返回ture
      var newDate = new Date(value.urgent_at);
      newDate.setMinutes(newDate.getMinutes() + 5);
      return newDate <= new Date()
    },
    isTimeSubtraction (item, ) {
      //发起时间加5分钟-当前时间=分钟
      var newDate = new Date(item.urgent_at);
      newDate.setMinutes(newDate.getMinutes() + 5);
      return newDate - new Date()
    },
    showCustomImagePreview (value, index) {
      this.customIndex = index;
      this.$createImagePreview({
        imgs: value,
        initialIndex: this.customIndex,
        loop: false,
        speed: 500,
        onChange: (i) => {
          this.customIndex = i
        },
        onHide: () => {
          console.log('hide')
        }
      }, (h) => {
        return h('div', {
          class: {
            'image-preview-custom-header': true
          },
          slot: 'header'
        }, this.customIndex + 1)
      }).show()
    },
    async setGood (data, value) {
      await setcommnet({ comment: value }, data.id).then(res => {
        this.$createToast({
          txt: '评价成功',
          type: 'correct'
        }).show()
        this.closePopupData();
      }).catch(() => {
        this.$createToast({
          txt: '评价失败',
          type: 'error'
        }).show()

      })
    },
    closePopupData () {
      //未读消息设置为已读消息
      console.log('1.重新拉取列表未读消息设置为已读消息\n2.重新获取消息未读数量')
      this.getFeedBackRecordInfo();
      this.feedBackRecord();
      this.showPopup = false
      this.openPopupData = {}
    },
    async getPopupData (value) {
      await getworkorderdetail(value.id).then(res => {
        this.openPopupData = res.data
        let desc=this.openPopupData.desc&&this.openPopupData.desc.replace(/\n/g,"<br/>").replace(/\s/g,"&nbsp;");
        if (desc&&desc.indexOf("<br/>") >= 0) {
          desc="<br/>"+desc
        }
        Object.assign(this.openPopupData,{desc})
        let response=this.openPopupData.response&&this.openPopupData.response.replace(/\n/g,"<br/>").replace(/\s/g,"&nbsp;");
        var httpReg = new RegExp("(http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&amp;*+?:_/=<>]*)?", "gi"); //用于判断文本内容超链接
        //文本地址变为a链接
        response =response&&response.replace(httpReg, function(httpText) {
          // let http=httpText.replace(/<[^>]*>|<\/[^>]*>/gm,'').replace('&nbsp;','')
          return `<a  href="javascript:;" >${httpText}</a>`;
        });
        Object.assign(this.openPopupData,{response})

        this.$forceUpdate()
        if (this.openPopupData.cooperation) {
          this.openPopupData.cooperation = JSON.parse(this.openPopupData.cooperation);
        }
      })

    },
    openurl: function(event){
      event.target.nodeName === 'A'&&openurl(event.srcElement.text)

    },
    openPopupDetail (value) {
      if(this.isOpenPopupDetail){
        this.showPopup = true
      this.getPopupData(value);
      }
      this.isOpenPopupDetail=true;
    },
    async IsInfo () {
      this.isLoding = true;
      await getUncheckedCount({}).then(res => {
        this.feedBackRecordInfo = res.data.count;
      }).then(()=>{
        this.isLoding = false;
        if (this.feedBackRecordInfo > 0) {
          this.customerActive = 1;
          this.feedBackRecord();
          this.announcementAlert()
        } else {
          this.feedBackRecordInfo = ''
          this.getCustomerProblemGroup()
          this.announcementAlert()
        }
      });
    },
    async announcementAlert () {
      await announcementAlert({}).then(res => {
        if (res.data.total != 0) {
          this.$createDialog({
            type: 'alert',
            title: res.data.items[0].title,
            content: res.data.items[0].context,
            // icon: 'cubeic-alert',
            confirmBtn: {
              text: '我知道了',
              active: true
            }
          }).show()
        }
      })
    },
    async getFeedBackRecordInfo () {
      await  getUncheckedCount({}).then(res => {
        this.feedBackRecordInfo = res.data.count;
        if (this.feedBackRecordInfo == 0) {
          this.feedBackRecordInfo = ''
        }
      });
    },
    async expedited (value) {
      await urgentworkorder(value.id).then(res => {
        if (res.status === 0) {
          this.$createToast({
            txt: '您的问题已加急处理中，会尽快给您回复',
            type: 'correct'
          }).show()
          //刷新反馈记录数据
        }
      });
      this.feedBackRecord();
    },
    async feedBackRecord () {
      await getworkorderlist({}).then(res => {
        this.isLoding = false;
        this.openRecordData = res.data.items;
        this.showNewData = false
        this.$nextTick(() => {
          this.showNewData = true
        })
        this.$forceUpdate()
        this.isexpeditedTimeOut();
      })

    },
    isexpeditedTimeOut () {
      //五分钟后刷新数据,可申请加急
      let time = 300000;
      let isexpedited = this.openRecordData.find(item => {
        if (!this.istimedisabled(item) && item.status === 0) {
          time = this.isTimeSubtraction(item)
          return true
        }
      });
      if (isexpedited) {
        var this_ = this;
        clearTimeout(this.Timeout_);
        return this.Timeout_ = setTimeout(function () { this_.feedBackRecord() }, time);
      }
    },
    customeradvisory () {
      this.isOpenProblem = false;
      this.getCustomerProblemGroup();
    },
    customerOpenProblemPage (value) {
      let QuerySerch = location.search
      if(QuerySerch.lastIndexOf("openProblem")!=-1){
        QuerySerch=QuerySerch.substring(0,QuerySerch.lastIndexOf("&openProblem"));
      }
      location.href = '/' + this.openPage[value.id] + QuerySerch+`&openProblem=${value.id}`
    },
    async openProblem (value) {
      if (value.id) {
        await  getCommonProblem({ type_id: value.id }).then(res => {
          this.isLoding = false;
          this.isOpenProblem = true
          this.openProblemData = res.data
          this.openProblemData.btnname = value.button
          this.openProblemData.id = value.id
        })
      }
    },
    async getCustomerProblemGroup () {
      if (this.customerProblemGroup.length === 0) {
        await getProblemType({}).then(res => {
          this.customerProblemGroup = res.data.items;
          this.isLoding = false;
          this.showPImg = false
          this.$nextTick(() => {
            this.showPImg = true
          })
          this.$forceUpdate()
        })      }
    },

  },
  beforeDestroy () {
  },

  watch: {
    customerActive () {
      this.isOpenProblem = false;
    }
  }
}
</script>

<style lang="less">

    .nonumber{
        color: grey;
        height: 60px;
        line-height: 60px;
        font-size:14px;
    }
    .rdataloading{
    .rdataloading-center{
        width: 85px;
        display: inline-block;
        .van-loading,.loadingtxt{
            height: 60px !important;
            line-height: 60px;
            float: left;
            display: inline-block;
        }
    }
    }
.customer-center-margin {
  margin: 25px 0;
}
.customer-loading {
  position: fixed;
  top: 38%;
  div {
    text-align: center;
    display: inline-block;
  }
}
.customer-openProblem {
  display: -ms-flexbox;
  padding: 10px 15px;
  box-sizing: border-box;
  line-height: 24px;
  background-color: #fff;
  color: #323233;
  font-size: 14px;
}
.PopupHg {
  height: 99%;
  overflow: auto;
  .problemimg {
    padding-right: 2px;
    max-height: 50px;
    max-width: 30%;
  }
}
.cube-popup {
  z-index: 3000 !important;
}
.cube-image-preview .cube-popup-mask {
  opacity: 1 !important;
}
.unread-dot {
  width: 50px;
  margin: auto
}
.unread-dot::after{
  margin-right: 5px
}
.van-button--disabled.disabled {
  border: grey;
  background-color: grey;
}
.openRecordData .van-cell {
  padding: 10px 5px;
}
.Expedited {
  border-right: 8px;
}

.showPopup {
  width: 86%;
  border-radius: 15px;
  height: 80%;
  padding: 29px 0 0 0;
  overflow: hidden;
  .van-col {
    word-break: break-all;
  }
  .closePopup {
    height: 28px;
    position: fixed;
    right: 5px;
    top: 2px;
    background-color: #fff;
  }
  .border-bottom-grey {
    border-bottom: 1px solid #ebedf0;
    margin: 10px 0;
    height: 0;
  }
  .col-br {
    height: 10px;
  }
  .tabbar[class*="van-hairline"]::after {
    border: none;
  }
}
.csp {
  .van-col.van-col--9 {
    text-align: center;
  }
}
</style>
